<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/layim/dist/css/layui.css">
</head>
<body>

</body>
<script src="/js/jquery.min.js"></script>
<script src="/js/reconnecting-websocket.min.js"></script>
<script src="/layim/dist/layui.js"></script>
<script>
  $(function () {
    //客服信息
    var customerService;
    $.ajax({
      url: '/customer_service/get_info',
      type: 'GET',
      dataType: 'json',
      async: false
    }).done(function (res) {
      customerService = res;
    });

    //加载layim信息
    layui.use('layim', function (layim) {
      layim.config({
         //设置为简约模式,不展示主面板
         brief: true
         //控制聊天面版最小化时、及最新消息提示层的相对right的px坐标
         ,minRight: '0px'
         //消息历史记录
         ,chatLog: layui.cache.dir + 'css/modules/layim/html/chatlog.html'
         ,init: {
           mine: customerService
         }
      });

      var socket = new ReconnectingWebSocket("ws://localhost:8080/web_socket?sessionId=0");

      socket.onopen = function () {
        console.log("连接成功");
      };
      socket.onclose = function () {
        console.log("关闭成功");
      };
      socket.onerror = function () {
        console.log("连接出错");
      };

      //发送成功
      layim.on('sendMessage', function (res) {
        //包含我发送的消息及我的信息
        var mine = res.mine;
        console.log('mine:' + JSON.stringify(mine));
        //对方的信息
        var to = res.to;
        console.log('to:' + JSON.stringify(to));
        //消息体
        var obj = {
          content: mine.content,//发送的消息内容
          to: to.fromid,//发送给游客
          from: 0,
          username: mine.username,
          avatar: mine.avatar
        }
        socket.send(JSON.stringify(obj));
        oldTime = new Date().getTime();
      });

      //收到消息
      socket.onmessage = function (res) {
        res = JSON.parse(res.data);
        //res为收到的值
        console.log(res);
        layim.getMessage(res);
        oldTime = new Date().getTime();
      }
    });
  });
</script>
</html>